﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.SessionState;

namespace eSSP_example.Utilities
{
    public class NetworkUtil
    {
        /// <summary>
        ///     getIpAddress
        /// </summary>
        /// <returns></returns>
        public static string getIpAddress()
        {
            string hostName = Dns.GetHostName(); // 获取本机主机名
            IPHostEntry ipEntry = Dns.GetHostEntry(hostName); // 根据主机名获取IP地址
            IPAddress ipAddress = ipEntry.AddressList[0]; // 获取第一个IPv4地址

            return  ipAddress.ToString();
        }

        /// <summary>
        ///     getIpV4Address
        /// </summary>
        /// <returns></returns>
        public static string getIpV4Address()
        {
            string hostName = Dns.GetHostName(); // 获取本机名
            IPAddress[] addresses = Dns.GetHostAddresses(hostName); // 获取本机IP地址列表

            foreach (IPAddress address in addresses)
            {
                if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) // 检查是否为IPv4地址
                {
                    Console.WriteLine("Local IPv4 Address: " + address.ToString());

                    return  address.ToString();
                }
            }

            return  string.Empty;
        }
    }
}
